package com.zw.separate.controller;

import com.zw.separate.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.zw.separate.model.User;
import com.zw.separate.model.WebResult;

@RestController
public class UserController {

    @Autowired
    private UserService service;

    /**
     * @Description 测试 查询所有用户  读取从库（读）
     * @Author zw
     * @Date 2021/5/19 16:18
     * @Param []
     * @Return wang.raye.separate.model.WebResult
    **/
    @RequestMapping("select")
    public WebResult select(){
        return WebResult.success(service.selectAll());
    }

    /**
     * @Description 测试 新增用户  读取主库（写）
     * @Author zw
     * @Date 2021/5/19 16:19
     * @Param [username, password]
     * @Return wang.raye.separate.model.WebResult
    **/
    @RequestMapping("add")
    public WebResult add(@RequestParam("username") String username, @RequestParam("password") String password){

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        if(service.addUser(user)){
            return WebResult.success();
        }else{
            return WebResult.error("添加失败");
        }
    }






    @RequestMapping("update")
    public WebResult update(
            @RequestParam("id") Integer id,
            @RequestParam("username") String username,
            @RequestParam("password") String password){

        User user = new User();
        user.setId(id);
        user.setUsername(username);
        user.setPassword(password);

        if(service.updateUser(user)){
            return WebResult.success();
        }else{
            return WebResult.error("更新失败");
        }
    }

    @RequestMapping("delete")
    public WebResult delete(int id){
        if(service.deleteByid(id)){
            return WebResult.success();
        }else{
            return WebResult.error("删除失败");
        }
    }

    @RequestMapping("test")
    public WebResult test(User user){
        try {
            if(service.insertAndUpdate(user)) {
                return WebResult.success();
            }else {
                return WebResult.error("失败,查看事务");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.error("失败:"+e.getMessage());
        }
    }
}
